package com.xingongchang.baolebei.model;


import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.external.androidquery.callback.AjaxStatus;
import com.google.gson.JsonObject;
import com.insthub.BeeFramework.model.BaseModel;
import com.insthub.BeeFramework.model.BeeCallback;
import com.insthub.BeeFramework.view.ToastView;
import com.xingongchang.baolebei.BaolebeiApp;
import com.xingongchang.baolebei.ErrorCodeConst;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.activity.SigninActivity;
import com.xingongchang.baolebei.fragment.ProfileFragment;
import com.xingongchang.baolebei.protocol.SESSION;
import com.xingongchang.baolebei.protocol.STATUS;
import com.xingongchang.baolebei.protocol.USER;
import com.xingongchang.baolebei.protocol.USER_INFO;
import com.xingongchang.baolebei.protocol.UserInfo_dis;

public class LoginModel extends BaseModel {

	private SharedPreferences shared;
	private SharedPreferences.Editor editor;
	//登陆
    public STATUS responseStatus;
    public int succeed;
    public UserInfo_dis info_dis;
    public SESSION session;
    
	
	public LoginModel(Context context) {
		super(context);
		shared = context.getSharedPreferences("userInfo", 0); 
		editor = shared.edit();
	}

	public void login(String name, String password) {
		String url = ProtocolConst.SIGNIN;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				LoginModel.this.callback(url, jo, status);
				try {
					
					responseStatus = STATUS.fromJson(jo.optJSONObject("status"));

                    Resources resource = mContext.getResources();
                    String user_not_exit = resource.getString(R.string.user_not_exist);
                    String invalid_password = resource.getString(R.string.invalid_password);
					
					if(responseStatus.succeed == ErrorCodeConst.ResponseSucceed) {
						
						JSONObject data = jo.optJSONObject("data");
						session = SESSION.fromJson(data.optJSONObject("session"));
						USER user = USER.fromJson(data.optJSONObject("user"));
						user.save();
						
						editor.putString("uid", session.uid);
	                    editor.putString("sid", session.sid);
	                    editor.commit();
						
					}
                    else if (responseStatus.error_code == ErrorCodeConst.InvalidUsernameOrPassword)
                    {
                        ToastView toast = new ToastView(mContext, invalid_password);
                        toast.setGravity(Gravity.CENTER, 0, 0);
                        toast.show();
                    }
					LoginModel.this.OnMessageResponse(url, jo, status);
					
				} catch (JSONException e) {
					 
					e.printStackTrace();
				}
			}

		};

		Map<String, String> params = new HashMap<String, String>();
		params.put("name", name);
		params.put("password", password);
		cb.url(url).type(JSONObject.class).params(params);
		aq.ajax(cb);
	}
	public void cancel(String uid, String sid) {
		String url = ProtocolConst.CANAEL;
		final String  uuid = uid;
		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {
				LoginModel.this.callback(url, jo, status);
				try {
					responseStatus = STATUS.fromJson(jo.optJSONObject("status"));
					USER user = ProfileFragment.userInfo(uuid);
					user.delete();
					editor.putString("uid", "");
	                editor.putString("sid", "");
	                editor.commit();
	               LoginModel.this.OnMessageResponse(url, jo, status);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		};

		
		Map<String, String> params = new HashMap<String, String>();
		JSONObject json = new JSONObject();
		
		try {
			json.put("sid", sid);
			json.put("uid", uid);
			JSONObject jso = new JSONObject();
			jso.put("session", json);
			params.put("json", jso.toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		cb.url(url).type(JSONObject.class).params(params);
		ProgressDialog pd = new ProgressDialog(mContext);
		Resources resource = mContext.getResources();
		String wait = resource.getString(R.string.hold_on);
		pd.setMessage(wait);
		aq.progress(pd).ajax(cb);
	}
	/**
	 * 第三方登陆
	 * @param openid
	 * @param act
	 * @param type
	 */
	public void snsLogin(String openid, String act,int type) {
		String url = ProtocolConst.DISANFANG;
		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				LoginModel.this.callback(url, jo, status);
				try {
					int STATUS = jo.optJSONObject("status").optInt("succeed",0);
					if(STATUS == 1) {
						JSONObject data = jo.optJSONObject("data");
						Log.i("Api", jo.toString());
						succeed= data.optInt("status", 0);
						Log.i("Api", succeed+"");
						if(succeed == 1){
							    SESSION session = SESSION.fromJson(data.optJSONObject("session"));
								editor.putString("uid", session.uid);
			                    editor.putString("sid", session.sid);
			                    editor.commit();
			                    
						}else if(succeed == 2){
						}
					}else if(STATUS==0){
						ToastView toast = new ToastView(mContext,responseStatus.error_desc);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
					LoginModel.this.OnMessageResponse(url, jo, status);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

		};
        
		Map<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("type", type+"");
		params.put("act", act);
		cb.url(url).type(JSONObject.class).params(params);
		aq.ajax(cb);
	}
	
	/**
	 * 更改第三方的头像和昵称等
	 */
	
	/**
	 * 更改第三方的头像和昵称等
	 */
	public void setLogininfo(String name,String pic,int sex,String nickName,String act,int type,final String openid,String email) {

		String url = ProtocolConst.DISANFANG;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				LoginModel.this.callback(url, jo, status);

				try {
					responseStatus = STATUS.fromJson(jo
							.optJSONObject("status"));

					if (responseStatus.succeed == 1) {
						    JSONObject data = jo.optJSONObject("data");
						    SESSION session = SESSION.fromJson(data.optJSONObject("session"));
							editor.putString("uid",session.uid);
		                    editor.putString("sid", session.sid);
		                    editor.commit();
						
						LoginModel.this.OnMessageResponse(url, jo, status);
					}

				} catch (JSONException e) {
					e.printStackTrace();
				}

			}

		};

		SESSION session = SESSION.getInstance();

		JSONObject requestJsonObject = new JSONObject();

		Map<String, String> params = new HashMap<String, String>();
		try {
			requestJsonObject.put("act",act);
			requestJsonObject.put("openid", openid);
			requestJsonObject.put("type",type);
			requestJsonObject.put("sex", sex);
			requestJsonObject.put("user_name", name);
			requestJsonObject.put("email",email);
			requestJsonObject.put("img", pic);
			requestJsonObject.put("nickname",nickName);
		} catch (JSONException e) {
		}
		params.put("json", requestJsonObject.toString());
		cb.url(url).type(JSONObject.class).params(params);
		ProgressDialog pd = new ProgressDialog(mContext);
		pd.setMessage(mContext.getResources().getString(R.string.hold_on));
		aq.progress(pd).ajax(cb);

	}
	/**
	 * 信息
	 */
	public void getInfo() {

		String url = ProtocolConst.DISANFANG;

		BeeCallback<JSONObject> cb = new BeeCallback<JSONObject>() {

			@Override
			public void callback(String url, JSONObject jo, AjaxStatus status) {

				LoginModel.this.callback(url, jo, status);

				try {
					STATUS responseStatus = STATUS.fromJson(jo
							.optJSONObject("status"));
					if (responseStatus.succeed == 1) {
						info_dis = UserInfo_dis.fromJson(jo.optJSONObject("data").optJSONObject("user"));
						BaolebeiApp.info_dis = info_dis;
						LoginModel.this.OnMessageResponse(url, jo, status);
					}

				} catch (JSONException e) {

					e.printStackTrace();
				}

			}

		};

		SESSION session = SESSION.getInstance();

		JSONObject requestJsonObject = new JSONObject();

		Map<String, String> params = new HashMap<String, String>();
		try {
			requestJsonObject.put("userid", session.uid);
		} catch (JSONException e) {

		}
		params.put("json", requestJsonObject.toString());
		cb.url(url).type(JSONObject.class).params(params);
		ProgressDialog pd = new ProgressDialog(mContext);
		pd.setMessage(mContext.getResources().getString(R.string.hold_on));
		aq.progress(pd).ajax(cb);
	}
	
}
